package com.dianrui.moonfire.activity;

import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.alipay.PayResult;
import com.dianrui.moonfire.event.OpenOrClose;
import com.dianrui.moonfire.util.EventBusConstants;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.util.MyUtil;
import com.dianrui.moonfire.util.NoDoubleClickUtils;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:行程结算
 * User: luoziyin
 * Date: 2020-8-17
 */
@SuppressWarnings("ALL")
public class RidingPriceActivity extends BaseActivity {
    private String orderIds, numbers, startTimes;
    private String isPayPlay;
    private String coupon_ids;
    private int couponNumbers;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.show_money)
    TextView showMoney;
    @BindView(R.id.bike_codes)
    TextView bikeCodes;
    @BindView(R.id.times)
    TextView times;
    @BindView(R.id.coupon_number)
    TextView couponNumber;

    @BindView(R.id.cb_balance)
    CheckBox cbBalance;
    @BindView(R.id.click_balance)
    RelativeLayout clickBalance;
    @BindView(R.id.click_wx)
    RelativeLayout clickWX;
    @BindView(R.id.click_zfb)
    RelativeLayout clickZfb;

    @BindView(R.id.yue_txt)
    TextView yueTxt;
    @BindView(R.id.zfb_txt)
    TextView zfbTxt;
    @BindView(R.id.wx_txt)
    TextView WxTxt;
    @BindView(R.id.yue_num)
    TextView yueNum;
    @BindView(R.id.cb_wx)
    CheckBox cbWx;
    @BindView(R.id.cb_zfb)
    CheckBox cbZfb;
    @BindView(R.id.click_coupon)
    RelativeLayout clickCoupon;
    @BindView(R.id.coupon_discount)
    TextView couponDiscount;


    @Override
    public int getContentViewId() {
        return R.layout.activity_ridingprice;
    }

    @Override
    public void initView() {
        customInit(true);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                orderIds = bundle.getString("id");
                numbers = bundle.getString("number");
                startTimes = bundle.getString("time");
                isPayPlay = bundle.getString("isPayPlays");

            }
        }
        title.setText(getString(R.string.riding_price_title));


        bikeCodes.setText(numbers);



        times.setText(startTimes);

        getOrderPrice();

        if ("1".equals(isPayPlay)) {
            openRawMusicEnd();
        }
    }

    @Override
    public void initData() {
    }

    private void getOrderPrice() {
        JsonObject orderPrice = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            orderPrice.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        orderPrice.addProperty("order_id", orderIds);
        XHttpRequest.getInstance().postRequests(Url.ORDERPRICE, orderPrice.toString(), new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) throws JSONException {
                if (!StringUtils.isEmpty(result)) {
                    final JSONObject jsonObject = new JSONObject(result);
                    if (null != jsonObject && !isFinishing()) {
                        if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                            String data = JsonUtils.getJsonStr(result, "data");

                            if ((jsonObject.optJSONObject("data").has("money"))) {
                                showMoney.setText(JsonUtils.getJsonStr(data, "money"));
                            }

                            if (StringUtils.isEmpty(jsonObject.optJSONObject("data").optString("tips"))) {
                                StringBuilder yueBuilder = new StringBuilder();
                                yueBuilder.append("(").append(JsonUtils.getJsonStr(data, "balance")).append(")");
                                yueNum.setText(yueBuilder.toString());
                            } else {
                                yueNum.setText(JsonUtils.getJsonStr(data, "tips"));
                            }

                            couponNumbers = jsonObject.optJSONObject("data").optInt("coupon_number");

                            StringBuilder couponNumberBuilder = new StringBuilder();
                            couponNumberBuilder.append("(").append(JsonUtils.getJsonStr(data, "coupon_number")).append(")");
                            couponNumber.setText(couponNumberBuilder.toString());


                            if ((jsonObject.optJSONObject("data").has("number"))) {
                                bikeCodes.setText(JsonUtils.getJsonStr(data, "number"));
                            }

                            if ((jsonObject.optJSONObject("data").has("run_time"))) {
                                times.setText(JsonUtils.getJsonStr(data, "run_time"));
                            }

                        } else {
                            ToastUtil.showToast(jsonObject.optString("message"));
                        }

                    }
                }

            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @OnClick({R.id.back, R.id.click_coupon, R.id.cb_balance, R.id.feedback_prized, R.id.click_balance, R.id.cb_wx, R.id.click_wx, R.id.cb_zfb, R.id.click_zfb, R.id.pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.click_coupon:
                Intent intent = new Intent(RidingPriceActivity.this, CouponListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("mc_id", coupon_ids);
                intent.putExtras(bundle);
                startActivityForResult(intent, 9);
                break;
            case R.id.cb_balance:
                cbBalance.setChecked(true);
                cbZfb.setChecked(false);
                cbWx.setChecked(false);
                break;
            case R.id.click_balance:
                cbBalance.setChecked(true);
                cbZfb.setChecked(false);
                cbWx.setChecked(false);
                break;
            case R.id.cb_wx:
                if ("0.00".equals(showMoney.getText().toString())) {
                    cbZfb.setChecked(false);
                    cbWx.setChecked(false);
                    ToastUtil.showToast(getString(R.string.zero_order_hint));
                    return;
                }
                cbBalance.setChecked(false);
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
                break;
            case R.id.click_wx:
                if ("0.00".equals(showMoney.getText().toString())) {
                    cbZfb.setChecked(false);
                    cbWx.setChecked(false);
                    ToastUtil.showToast(getString(R.string.zero_order_hint));
                    return;
                }
                cbBalance.setChecked(false);
                cbZfb.setChecked(false);
                cbWx.setChecked(true);
                break;

            case R.id.cb_zfb:
                if ("0.00".equals(showMoney.getText().toString())) {
                    cbZfb.setChecked(false);
                    cbWx.setChecked(false);
                    ToastUtil.showToast(getString(R.string.zero_order_hint));
                    return;
                }
                cbBalance.setChecked(false);
                cbWx.setChecked(false);
                cbZfb.setChecked(true);
                break;

            case R.id.click_zfb:
                if ("0.00".equals(showMoney.getText().toString())) {
                    cbZfb.setChecked(false);
                    cbWx.setChecked(false);
                    ToastUtil.showToast(getString(R.string.zero_order_hint));
                    return;
                }
                cbBalance.setChecked(false);
                cbWx.setChecked(false);
                cbZfb.setChecked(true);
                break;
            case R.id.feedback_prized:
                startActivity(new Intent(RidingPriceActivity.this, TroubleFeedActivity.class).putExtra("mv_id", orderIds));
                break;
            case R.id.pay:
                if (cbBalance.isChecked()) {
                    startBalancePay();
                } else if (cbWx.isChecked()) {
                    startWxPay();
                } else if (cbZfb.isChecked()) {
                    startZfbPay();
                }
                break;

            default:
                break;
        }
    }


    //用余额支付
    private void startBalancePay() {
        showLoadingDialog(getString(R.string.paying));
        JsonObject pay = new JsonObject();
        pay.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        pay.addProperty("payment_mode", "1");//支付方式（必传）1余额，2微信，3支付宝，4银行卡
        pay.addProperty("money", showMoney.getText().toString());
        pay.addProperty("type", "3");//支付类型（必传）1账户充值，2缴纳押金，3订单支付，4缴纳罚款
        pay.addProperty("ids", orderIds);
        if (!StringUtils.isEmpty(coupon_ids)) {
            pay.addProperty("mc_id", coupon_ids);
        }
        XHttpRequest.getInstance().postRequests(Url.PAY, pay.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                EventBus.getDefault().post(new OpenOrClose(false));
                                EventBus.getDefault().post(EventBusConstants.REFRESH_CAR_LIST);
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(PaySuccessActivity.class);
                                finish();
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));//账户余额不足

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //用微信支付
    private void startWxPay() {
        showLoadingDialog(getString(R.string.paying));
        JsonObject pay = new JsonObject();
        pay.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        pay.addProperty("payment_mode", "2");
        pay.addProperty("money", showMoney.getText().toString());
        pay.addProperty("type", "3");
        pay.addProperty("ids", orderIds);
        if (!StringUtils.isEmpty(coupon_ids)) {
            pay.addProperty("mc_id", coupon_ids);
        }
        XHttpRequest.getInstance().postRequests(Url.PAY, pay.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                IWXAPI msgApi = WXAPIFactory.createWXAPI(RidingPriceActivity.this, Constant.WXAppID, true);
                                if (!msgApi.isWXAppInstalled()) {
                                    ToastUtil.showToast(getString(R.string.wx_installed));
                                }
                                PayReq payReq = new PayReq();
                                payReq.appId = jsonObject.optJSONObject("data").optString("appid");
                                payReq.partnerId = jsonObject.optJSONObject("data").optString("partnerid");
                                payReq.prepayId = jsonObject.optJSONObject("data").optString("prepayid");
                                payReq.packageValue = jsonObject.optJSONObject("data").optString("package");
                                payReq.nonceStr = jsonObject.optJSONObject("data").optString("noncestr");
                                payReq.timeStamp = jsonObject.optJSONObject("data").optString("timestamp");
                                payReq.extData = "orderPay";
                                payReq.sign = jsonObject.optJSONObject("data").optString("sign");
                                msgApi.sendReq(payReq);
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));//账户余额不足
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //用支付宝支付
    private void startZfbPay() {
        showLoadingDialog(getString(R.string.paying));
        JsonObject pay = new JsonObject();
        pay.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        pay.addProperty("payment_mode", "3");
        pay.addProperty("money", showMoney.getText().toString());
        pay.addProperty("type", "3");
        pay.addProperty("ids", orderIds);
        if (!StringUtils.isEmpty(coupon_ids)) {
            pay.addProperty("mc_id", coupon_ids);
        }
        XHttpRequest.getInstance().postRequests(Url.PAY, pay.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                if (!MyUtil.checkAliPayInstalled(RidingPriceActivity.this)) {
                                    ToastUtil.showToast(getString(R.string.zfb_installed));
                                    return;
                                }
                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(RidingPriceActivity.this);
                                        final Map<String, String> res = alipay.payV2(jsonObject.optJSONObject("data").optString("contents"), true);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                PayResult payResult = new PayResult(res);
                                                String resultStatus = payResult.getResultStatus();
                                                if (Constant.ALIPAY_CODE.equals(resultStatus)) {
                                                    ToastUtil.showToast(getString(R.string.pay_success));
                                                    EventBus.getDefault().post(new OpenOrClose(false));
                                                    EventBus.getDefault().post(EventBusConstants.REFRESH_CAR_LIST);
                                                    JumpActivitys(PaySuccessActivity.class);
                                                    finish();
                                                } else {
                                                    ToastUtil.showToast(getString(R.string.pay_failed));
                                                }
                                            }
                                        });
                                    }

                                };
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //结束用车的语音
    private void openRawMusicEnd() {
        MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.returncar);
        mediaPlayer1.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 9) {
            if (!StringUtils.isEmpty(data.getStringExtra("coupon_id"))) {
                coupon_ids = data.getStringExtra("coupon_id");//获取到了优惠劵的id
            } else {
                coupon_ids = "";//id是空的
            }
            if (!StringUtils.isEmpty(data.getStringExtra("moneys"))) {
                String coupoen = data.getStringExtra("moneys");
                couponDiscount.setText("-￥" + coupoen);
            } else {
                couponDiscount.setText("");
            }
            //是否禁用其它第三方支付方式，0否，1是
            String isDisable = data.getStringExtra("isDisable");
            if (!StringUtils.isEmpty(isDisable)) {
                if (isDisable.equals("1")) {
                    clickBalance.setEnabled(true);
                    cbBalance.setEnabled(true);
                    clickZfb.setEnabled(false);
                    clickWX.setEnabled(false);
                    cbWx.setEnabled(false);
                    cbZfb.setEnabled(false);
                    yueTxt.setTextColor(Color.BLACK);
                    zfbTxt.setTextColor(Color.GRAY);
                    WxTxt.setTextColor(Color.GRAY);
                } else {
                    clickBalance.setEnabled(true);
                    clickZfb.setEnabled(true);
                    clickWX.setEnabled(true);
                    cbBalance.setEnabled(true);
                    cbWx.setEnabled(true);
                    cbZfb.setEnabled(true);
                    yueTxt.setTextColor(Color.BLACK);
                    zfbTxt.setTextColor(Color.BLACK);
                    WxTxt.setTextColor(Color.BLACK);
                }
            } else {
                clickBalance.setEnabled(true);
                clickZfb.setEnabled(true);
                clickWX.setEnabled(true);
                cbBalance.setEnabled(true);
                cbWx.setEnabled(true);
                cbZfb.setEnabled(true);
                yueTxt.setTextColor(Color.BLACK);
                zfbTxt.setTextColor(Color.BLACK);
                WxTxt.setTextColor(Color.BLACK);
            }
        }
    }
}
